package com.model
{
	import flash.display.Bitmap;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	
	public class BitmapLoader
	{
		private var _imageBitmap:Bitmap = null;
		private var _completeHandler:Function = null;
		private var _progressHandler:Function = null;
		private var _timeOutHandler:Function = null
		private var _timeOut:Timer = null;
		private var _loadImageTimer:Timer = null;
		
		private var _url:String = null;
		
		
		public function BitmapLoader(imageURL:String = null, completeHandler:Function = null, progressHandler:Function = null, timeOutHandler:Function = null)
		{
			_url = imageURL;
			_timeOut = new Timer(30 * 1000, 1);
			_timeOut.addEventListener(TimerEvent.TIMER, onTimeOut);
			
			_loadImageTimer = new Timer(3000, 10);
//			_loadImageTimer.addEventListener(TimerEvent.TIMER, function (e:Event):void {loadImage(_url)}); 
//			_loadImageTimer.addEventListener(TimerEvent.TIMER_COMPLETE, function (e:Event):void {_loadImageTimer = null;}); 
			
			_completeHandler = completeHandler;
			_progressHandler = progressHandler;
			_timeOutHandler = timeOutHandler;
			
			if(imageURL)
				loadImage(imageURL);		
		}

		public function loadImage(imageURL:String):void
		{
			var imageLoader:Loader = new Loader();
			imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
			imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageProgressHandle);
			imageLoader.contentLoaderInfo.addEventListener(FaultEvent.FAULT, function (e:Event):void{Alert.show(e.toString());});
			imageLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, handleIOErrorEvent);
			imageLoader.load(new URLRequest(imageURL));
			_timeOut.start();
		}
		
		private function handleIOErrorEvent(e:IOErrorEvent):void {
			// Check if the result messege file not found then the converting threed not finished
			_timeOut.reset();
			if(_loadImageTimer != null && !_loadImageTimer.running) {
				_loadImageTimer.start();
			}	
		}
		private function onTimeOut(event:TimerEvent):void
		{
			_timeOut.reset();
			if(_timeOutHandler != null)
				_timeOutHandler.call(null);
		}

		private function imageProgressHandle(e:ProgressEvent):void
		{
			_timeOut.reset();
			_timeOut.start();
			if(_progressHandler != null)
				_progressHandler(e);
		}
		protected function onImageLoaded(event:Event):void
		{
			_imageBitmap = event.target.content;
			_loadImageTimer.reset();
			_timeOut.reset();
			if(_completeHandler != null)
				_completeHandler.call(null);
		}
		
		public function get bitmap():Bitmap
		{
			return _imageBitmap;
		}
	}
}